//
//  OAuthViewController.swift
//  Weibo T
//
//  Created by mac on 15/11/28.
//  Copyright © 2015年 陈肖坤. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close() {
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    @objc private func defaultAccount() {
        //本地代码调用  js
        let jsString = "document.getElementById('userId').value = '13526163920',document.getElementById('passwd').value = 'chenxiaokun'"
    webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充 ", style: .Plain, target: self, action: "defaultAccount")
        loadOAuthPage()
        
    }
    
    private func loadOAuthPage() {
        //https://api.weibo.com/oauth2/authorize
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        if let url = NSURL(string: urlString) {
            let request = NSURLRequest(URL: url)
            //使用webView加载网页
            webView.loadRequest(request)
            
        }
        
    }

}
extension OAuthViewController:UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //js 调用本地代码
        let urlString = request.URL?.absoluteString ?? ""
//        print(request)
        //屏蔽掉不希望加载的页面
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        
        if !urlString.hasPrefix("http://www.itcast.cn") {
            return false
        }
        //程序如果走到这里  就只有包含回调的url才能运行到此
//        print(urlString)
        //获取授权码
        guard let query = request.URL?.query else {
            //获取不到参数列表
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        //        print(code)
        //获取到code码
        //请求用户token
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }

        //发出通知页面切换
        //发出切换页面消息
        self.dismissViewControllerAnimated(false) { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
            print("dgfhjk")
            //          SVProgressHUD.showSuccessWithStatus("登录成功")
                        }

        }
        return false
    }
}


